package com.lyhlmj.oop_client.Style.Buttons.PlayFrameButton;

import com.lyhlmj.oop_client.ClientOperation.ClientUtil.Client;
import com.lyhlmj.oop_client.Frames.WaitFrame.WaitFrame;
import com.lyhlmj.oop_client.Style.Buttons.GeneralButton;
import com.lyhlmj.oop_client.Utils.Request;
import org.json.JSONObject;

import javax.swing.*;

public class ConcedeButton extends GeneralButton {
    private Client client = Client.client;

    public ConcedeButton(String title) {
        super(title);
    }

    //设置认输事件
    public void doConcede(JFrame frame) {
        //用户点击认输按钮，执行认输操作
        int flag = JOptionPane.showConfirmDialog(frame, "您是否确定认输？",
                "提示!", JOptionPane.YES_NO_OPTION,
                JOptionPane.INFORMATION_MESSAGE);

        //用户选择确认
        if (JOptionPane.YES_OPTION == flag) {
//            System.out.println("用户"+client.getUsername()+"认输！");
            //向后端发送认输请求
            JSONObject jsonReq = Request.getJsonObject("concede", "username", client.getUsername(), "chatRoomId", client.getChatRoomId());
            client.send(jsonReq, new Client.Callback() {
                @Override
                public void onResult(int status, String reason, JSONObject data) {
                    if (status == 0) {
                        JOptionPane.showMessageDialog(frame, "您已认输。您可以选择重新开始游戏！");
                    }
                }
            });

            //关闭对局相关的线程
            Client.client.getPlayStatusTask.doStop();//关闭获取游戏状态的线程
            Client.client.getChatInfoTask.doStop(); // 控制消息接收线程，令其退出

            //删除client内部的用户对局信息
            Client.client.setChatRoomId("");
            Client.client.setPlayers(null);
            Client.client.setPlayId(0);
            Client.client.getChatInfoTask = null;
            Client.client.getPlayStatusTask = null;

            //关闭当前界面，回到匹配界面，用户不登出，可以重新匹配
            frame.setVisible(false);
            WaitFrame.initial();
        } else {
            return;
        }
    }
}
